//
//  NetworkTools.swift
//  Weibo1.0
//
//  Created by 黄礼潮 on 16/2/18.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit
import AFNetworking

enum CZRequestMethod: String {

   case GET = "GET"
    
   case  POST = "POST"

}

class NetworkTools: AFHTTPSessionManager {
    
 /// MARK --- 应用程序信息
    private let appKey = "1502115466"
    private let appSecret = "aaf4e19bef12ad18c79274ad6b0e96a8"
    private let redirectUrl = "http://www.baidu.com"
    
    /// 网络请求完成回调，类似于 OC 的 typeDefine
    typealias CZRequestCallBack = (result:AnyObject?,error:NSError?)->()
    
    static let shardTools: NetworkTools = {
    
        let tools = NetworkTools(baseURL: nil)
        
        // 设置反序列化数据格式 - 系统会自动将 OC 框架中的 NSSet 转换成 Set
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
    
        return tools
    }()
    
}

// MARK: - OAuth 相关方法
extension NetworkTools {
    
 /// - see: [https://api.weibo.com/oauth2/authorize](https://api.weibo.com/oauth2/authorize)

    var oauthURL : NSURL {
    
     let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
     return NSURL(string: urlString)!
   }
    
    /// 加载 AccessToken
    func loadAccessToken(code: String, finished:CZRequestCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
    }


}

extension NetworkTools {

  
  private   func request(method:CZRequestMethod, URLString:String, parameters:[String:AnyObject]?,finished:CZRequestCallBack){
    
        let success = { (task:NSURLSessionDataTask, result:AnyObject?) -> Void in
            
            if let result = result as?[String:AnyObject]{
            
                  finished(result: result, error: nil)
            }
        }
        
        let failure = {(task:NSURLSessionDataTask?, error:NSError) -> Void in
            
            // 在开发网络应用的时候，错误不要提示给用户，但是错误一定要输出！
            print(error)
            finished(result: nil, error: error)
        
        }
    //// 'GET(_:parameters:success:failure:)' is deprecated
        
        if method == .GET {
    
           GET(URLString, parameters: parameters, success: success, failure: failure)
            
        }else{
        
           POST(URLString, parameters: parameters, success: success, failure: failure)
        }
        
    
    }
    

}




